package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.service.ManagerService;
import com.liuzhilin.util.Response;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/managerArticleNotPassBatch")
public class ManagerArticleNotPassBatch extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        // 从请求体中获取JSON数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String json = sb.toString();

        // 解析JSON数据
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> data = objectMapper.readValue(json, Map.class);
            List<Map<String, String>> articles = (List<Map<String, String>>) data.get("articles");
            String adminName = (String) data.get("adminName");
            boolean success = true;
            for (Map<String, String> article : articles) {
                String writer = article.get("writer");
                String title = article.get("title");
                String category = article.get("category");

                if (!ManagerService.notPassArticle(writer, title, category)) {
                    success = false;
                    break;
                }
                if(adminName!=null){
                    ManagerService.recordOperationLog(adminName, "判定用户"+writer+"发布在"+category+"标题为"+title+"的文章不通过",writer);
                }
            }

            if (success) {
                out.print("{\"success\": true}");
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "部分或全部审核不通过失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "请求格式错误");
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}